<script setup lang="ts">
import {ref, onMounted, onBeforeUnmount} from "vue";
import {useTransition} from '@vueuse/core'
import {storage} from "@/utils/storage.ts";


let cpuUsed = ref(0)
const cpuUsedValue = useTransition(cpuUsed, {
  duration: 1500,
})
let cpuSys = ref(0)
const cpuSysValue = useTransition(cpuSys, {
  duration: 1500,
})
setInterval(() => {
  sendMessage()
}, 1000)
const ws = ref(WebSocket);
const username = storage('username').get()

function connectWebSocket() {
  ws.value = new WebSocket('ws://127.0.0.1:8088/webSocket/' + username);

  ws.value.onopen = function (event) {
    console.log('WebSocket connected:', event);
  };

  ws.value.onerror = function (error) {
    console.error('WebSocket error:', error);
  };

  ws.value.onmessage = function (event) {
    // console.log('WebSocket message received:', event.data);
    let jsonData = JSON.parse(event.data);
    cpuUsed.value = jsonData.used
    cpuSys.value = jsonData.sys
  };
  ws.value.onclose = function () {
    console.log('WebSocket disconnected');
    ws.value = null;
  };
}

function sendMessage() {
  if (ws.value && ws.value.readyState === 1) {
    ws.value.send('HomeView');
  }
}

function closeWebSocket() {
  if (ws.value) {
    ws.value.close();
  }
}

onMounted(() => {

  connectWebSocket()
  sendMessage()
})

onBeforeUnmount(() => {
  closeWebSocket()
})
</script>

<template>
  <el-row :gutter="10">
    <el-col :span="6">
      <el-card>
        <el-row :gutter="10">
          <el-col :span="8">
            <el-statistic style="justify-content: center" title="CPU用户占用率" :value="cpuUsedValue"/>
          </el-col>
          <el-col :span="8">
            <el-statistic style="justify-content: center" title="CPU系统占用率" :value="cpuSysValue"/>
          </el-col>
          <el-col :span="8">
            <el-statistic style="justify-content: center" title="不写了" :value="outputValue"/>
          </el-col>
        </el-row>
      </el-card>
    </el-col>
    <el-col :span="6">
      <div class="grid-content ep-bg-purple-light">
        <el-card>
          <div id="12" style="width: 100%;height:5vh;"></div>
        </el-card>
      </div>
    </el-col>
    <el-col :span="6">
      <div class="grid-content ep-bg-purple">
        <el-card>
          <div id="123" style="width: 100%;height:5vh;"></div>
        </el-card>
      </div>
    </el-col>
    <el-col :span="6">
      <div class="grid-content ep-bg-purple-light">
        <el-card>
          <div id="1432" style="width: 100%;height:5vh;"></div>
        </el-card>
      </div>
    </el-col>
  </el-row>
</template>

<style scoped lang="scss">

</style>